import ConfigParser
import logging
import logging.config
import os.path
import random
import re
import string
import sys

from ConfigParser import NoOptionError

######################
# Conf file handling #
######################
p = os.path.dirname(__file__)
confparser = ConfigParser.ConfigParser()
config_files = ['/etc/TiVoToDo.conf', os.path.join(p, 'TiVoToDo.conf')]
configs_found = confparser.read(config_files)

################
# Log handling #
################
def init_logging():
    if (confparser.has_section('loggers') and
        confparser.has_section('handlers') and
        confparser.has_section('formatters')):

        logging.config.fileConfig(config_files)

    else:
        logging.basicConfig(level=logging.INFO)

##############################
# Output file specifications #
##############################
output_dir = os.path.join(p, 'output')
obj_dir = os.path.join(p, 'cache')
cache_file = os.path.join(p, 'cache', 'Shows.cache')
html_file = os.path.join(p, 'Debug.html')
xml_file = os.path.join(p, 'Debug.xml')

####################
# Static variables #
####################
base_url = 'https://www3.tivo.com'                  # Production TiVo website
beta_url = 'https://www3-beta.tivo.com'             # Beta TiVo website
indx_url = '/tivo-tco/index.do'                     # TCO login page
reco_url = '/tivo-tco/recoptions.do?offerId='       # Record with Options
srch_url = '/tivo-tco/search/advanced.do?'          # Advanced Search page
show_url = '/tivo-tco/program/show.do?'             # Show detail page
spwo_url = '/tivo-tco/confrecoptions.do?'           # Season Pass w/Options
spm_url = '/apps/spm.do?'                           # Season Pass Manager page
todo_url = '/tivo-tco/go.do?def=todo.content.body'  # To Do List page

#####################
# Dynamic variables #
#####################
clu = []            # List of lists: Channel LineUps
rdl = []            # List of lists: To Do List Raw Data
spm = []            # List of lists: Season Pass Manager
tivo_clu = []       # List of lists: Channel LineUps

shows = {}          # Dictionary to hold show details
tivos = {}          # Dictionary to hold TiVo TSNs
tuners = {}         # Dictionary to hold TiVo tuner activity

get_clu = False     # Collect Channel Lineup flag
guid = ''.join([random.choice(string.letters) for i in range(10)])
free_tuner = ''     # A free tuner on a TiVo
noShows = False     # End of To Do List trigger
our_ip = ''
rdi_cdtl = None     # Channel detail
rdi_date = None     # Month / Date (MM/dd)
rdi_dttm = None     # Datetime object (year, month, day, hour, minute)
rdi_dura = None     # Show duration in minutes
rdi_edtl = None     # Episode detail
rdi_lchn = None     # Long channel name
rdi_new  = False    # New Show indicator
rdi_rtyp = None     # Recording type
rdi_schd = None     # Season Pass original schedule
rdi_sdtl = None     # Show detail
rdi_skey = None     # Shows key
rdi_spoc = None     # Season Pass on other channels
rdi_spol = None     # Season Pass original link
rdi_time = None     # Recording start time (hh:mm am/pm)
rdi_titl = None     # Show title
rdi_tivo = None     # TiVo name show was recorded on
rdi_ttsn = None     # TiVo tsn show was recorded on
rdi_wday = None     # Week day
spm_chan = None     # Season Pass channel
spm_prty = None     # Season Pass priority
spm_sIds = None     # Season Pass ID
spm_titl = None     # Season Pass title

###############################
# Conf file parsing functions #
###############################
def init(argv):
    global config_files
    configs_found = confparser.read(config_files)
    if not configs_found:
        debug(0, 'ERROR: TiVoToDo.conf does not exist.\n' +
                 'You must create this file before running TiVoToDo.')
        sys.exit(1)

def get_email():
    if not confparser.has_section('email'):
        debug(0, 'TiVo account email required in TiVoToDo.conf')
        sys.exit(1)
    em = confparser.get('email', 'email')
    if not em:
        debug(0, 'Please update the TiVoToDo.conf email section ' + \
              'with an email address.')
        sys.exit(1)
    return(em)

def get_password():
    if not confparser.has_section('password'):
        debug(0, 'TiVo account password required in TiVoToDo.conf')
        sys.exit(1)
    pw = confparser.get('password', 'password')
    if not pw:
        debug(0, 'Please update the TiVoToDo.conf password section ' + \
              'with a password.')
        sys.exit(1)
    return(pw)

def get_schd_offset():
    try:
        cs = confparser.get('overlap_protection', 'clipping')
        if not cs:
            raise ValueError
    except (NoOptionError, ValueError):
        cs = confparser.get('DEFAULT', 'clipping')
    if cs.title() == 'Enabled':
        return(cs.title(), -5)
    elif cs.title() == 'Disabled':
        return(cs.title(), 0)

def get_incl():
    il = {}
    list = [v.strip() for v in confparser.get('include_tivos', 
                                              'incl_tivo').split(',')]
    if list != ['']:
        for item in list:
            il[item.split('/')[0]] = item.split('/')[1]
    return(il)

def get_excl():
    el = [v.strip() for v in confparser.get('exclude_tivos', 
                                            'excl_tivo').split(',')]
    return(el)

def get_debug():
    try:
        return(confparser.getboolean('debug', 'debug'))
    except (NoOptionError, ValueError):
        return False
    
def get_output(type):
    try:
        list = confparser.get('output', type)
        if not list:
            raise ValueError
        else:
            list = re.split('\W+', list)
            list = [item.title() for item in list]
    except (NoOptionError, ValueError):
        list = confparser.get('DEFAULT', type)
        list = re.split('\W+', list)
    return(list)

def get_tivo_count():
    try:
        return(confparser.getint('min_tivo_count', 'min_tivos'))
    except (NoOptionError, ValueError, TypeError):
        return(confparser.getint('DEFAULT', 'min_tivos'))

def get_broadcast():
    try:
        address = confparser.get('broadcast_address', 'broadcast')
        if not address:
            raise ValueError
        else:
            return address
    except (NoOptionError, ValueError):
        return(confparser.get('DEFAULT', 'broadcast'))

def get_beta():
    try:
        return(confparser.getboolean('beta_participant', 'beta'))
    except (NoOptionError, ValueError):
        return(confparser.get('DEFAULT', 'beta'))

def SP_opts():
    try:
        sp_showType = confparser.get('Season_Pass', 'showType').upper()
        if not sp_showType:
            raise ValueError
    except (NoOptionError, ValueError):
        sp_showType = confparser.get('DEFAULT', 'showType')

    try:
        sp_priority = confparser.get('Season_Pass', 'priority').upper()
        if not sp_priority:
            raise ValueError
    except (NoOptionError, ValueError):
        sp_priority = confparser.get('DEFAULT', 'priority')

    try:
        sp_quality = confparser.get('Season_Pass', 'quality').upper()
        if not sp_quality:
            raise ValueError
    except (NoOptionError, ValueError):
        sp_quality = confparser.get('DEFAULT', 'quality')

    try:
        sp_keepAtmost = confparser.getint('Season_Pass', 'keepAtmost')
    except (NoOptionError, ValueError, TypeError):
        sp_keepAtmost = confparser.getint('DEFAULT', 'keepAtmost')

    try:
        sp_keepUntil = confparser.getint('Season_Pass', 'keepUntil')
    except (NoOptionError, ValueError, TypeError):
        sp_keepUntil = confparser.getint('DEFAULT', 'keepUntil')

    try:
        sp_start = confparser.getint('Season_Pass', 'start')
    except (NoOptionError, ValueError, TypeError):
        sp_start = confparser.getint('DEFAULT', 'start')

    try:
        sp_stop = confparser.getint('Season_Pass', 'stop')
    except (NoOptionError, ValueError, TypeError):
        sp_stop = confparser.getint('DEFAULT', 'stop')

    sp_email = confparser.get('Season_Pass', 'email')
    
    rec_opts = ({'recType': 'seasonpass',
                 'originalUrl': '',
                 'showType': sp_showType,
                 'priority': sp_priority,
                 'quality': sp_quality,
                 'keepAtmost': sp_keepAtmost,
                 'keepUntil': sp_keepUntil,
                 'start': sp_start,
                 'stop': sp_stop,
                 'email': sp_email
                 })
    return(rec_opts)

def getGUID():
    return guid

#####################
# Derived variables #
#####################
csv_list = get_output('csv')
display_list = get_output('display')
offset = get_schd_offset()
